<?php

/**
 * JdId  
 */
class PlatformAPIClient_Jdid extends PlatformAPIClient_Abstract {
    
    /**
     * client
     * @var type 
     */
    private $_client = null;
    
    /**
     * 初始化
     * @param type $option
     */
    public function __construct($option = array()) {
        
        parent::__construct($option);
        
        require_once dirname(dirname(__FILE__)) . '/third-lib/JdidClient.php';
        $c = new JdidClient();
        $c->appKey = $this->_option['app_key'];
        $c->appSecret = $this->_option['app_secret'];
        $c->accessToken = $this->_option['token'];
        $c->serverUrl = "https://open.jd.id/api";
        if (!empty($option['debug_mode'])) {
            $c->debugMode = true;
        }
        $this->_client = $c;
    }
    
    /**
     * 获取指定订单信息
     * @param type $orderId
     * @return type
     * @throws Exception
     */
    public function getOrder($orderId) {
        
        $orders = $this->getBatchOrders([$orderId]);
        return $orders ? $orders[0] : [];
    }
    
    /**
     * 批量获取指定订单信息
     * @staticvar int $batchSize
     * @param type $orderIds
     * @return type
     * @throws Exception
     */
    public function getBatchOrders($orderIds) {
        static $batchSize = 10;
        
        $orderIdsGroup = array_chunk($orderIds, $batchSize);
        $dataset = [];
        foreach ($orderIdsGroup as $ids) {
            $params = $ids;
            $this->_client->method = "epi.popOrder.getOrderInfoListForBatch";
            $this->_client->param_json = json_encode($params);
            $resp = $this->_client->call();
            $model = $this->_parseResponse($resp, 'get jd.id order');
            $orders = json_decode($model, true);
            if ($orders && is_array($orders)) {
                $dataset = array_merge($dataset, $orders);
            }
        }
        return $dataset;
    }

    /**
     * 获取订单列表
     * @param type $conditions
     * @return type
     * @throws Exception
     */
    public function getOrderList($conditions) {

        // get orders by condition
        $params = [
            "startRow" => 0, 
            "createdTimeBegin" => time() - 86400,
        ];
        $params = array_merge($params, $conditions);
        $this->_client->method = "epi.popOrder.getOrderIdListByCondition";
        $this->_client->param_json = json_encode($params);
        $resp = $this->_client->call();
        $orderIds = $this->_parseResponse($resp, 'get jd.id order list');
        return $this->getBatchOrders($orderIds);
    }
    
    /**
     * 获取当前库存量
     * @param type $sku
     * @return type
     */
    public function getStock($sku) {
        
        // get current stock
        $skuIds = [
            ["skuId" => intval($sku['sku_id'])],
        ];
        $params = ['jsonStr' => json_encode($skuIds)];
        $this->_client->method = "epi.ware.openapi.warestock.queryWareStockList";
        $this->_client->param_json = json_encode($params);
        $resp = $this->_client->call();
        return $this->_parseResponse($resp, 'get sku stock');
    }

    /**
     * 设置库存
     * @param type $sku
     * @param type $stock
     */
    public function setStock($sku, $stock) {
        
        $skuStocks = [
            ["skuId" => intval($sku['sku_id']), "realNum" => intval($stock)],
        ];
        $params = ['jsonStr' => json_encode($skuStocks)];
        $this->_client->method = "epi.ware.openapi.warestock.updateWareStock";
        $this->_client->param_json = json_encode($params);
        $resp = $this->_client->call();
        return $this->_parseResponse($resp, 'set sku stock');
    }
    
    /**
     * 解析返回数据
     * @param type $resp
     */
    private function _parseResponse($resp, $actionName = '') {
        
        $resp = json_decode($resp, true);
        $code = $resp['openapi_code'];
        if (!$resp || $code !== 0) {
            throw new Exception($actionName.' failed. api message: '.$resp['openapi_msg']);
        }
        $data = json_decode($resp['openapi_data'], true);
        if (!$data['success']) {
            throw new Exception($actionName.' failed. data message: '.$data['message']);
        }
        return $data['model'];
    }

}